package com.sky.controller.user;

import com.sky.Service.UserService;
import com.sky.constant.JwtClaimsConstant;
import com.sky.context.BaseContext;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.HashMap;

@Slf4j
@Api(tags = "用户登录相关接口")
@RestController
@RequestMapping("/user/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private JwtProperties jwtProperties;


    /**
     * 用户登录
     *
     * @param userLoginDTO
     * @return
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Result<UserLoginVO> userLogin(@RequestBody UserLoginDTO userLoginDTO) throws IOException {
        System.out.println("微信用户登录:" + userLoginDTO);
        User user=userService.login(userLoginDTO);

        //为微信用户生成JWT令牌
        HashMap<String, Object> claims= new HashMap<>();
        //设置自定义声明  用户唯一标识id
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        //生成token
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);
        log.info("生成的token为:{}",token);
        //构造响应对象
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token)
                .build();
        System.out.println("微信用户登录成功:"+userLoginVO);
        return Result.success(userLoginVO);
    }

    /**
     * 用户退出登录
     * @return
     */
    @ApiOperation(("用户退出登录"))
    @PostMapping("/logout")
    public Result<String> userLogout(){
        log.info("用户退出登录");
        //清除当前用户id
        BaseContext.clearCurrentUserId();
        return Result.success();
    }


}
